import React, { useState } from 'react';
import { usePost } from '../contexts/PostContext';
import {
  Box,
  TextField,
  Button,
  Paper,
  Typography,
  CircularProgress,
} from '@mui/material';

export const CreatePostForm: React.FC = () => {
  const { createPost, loading } = usePost();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !content.trim()) {
      setError('标题和内容不能为空');
      return;
    }

    try {
      setError(null);
      await createPost(title, content);
      setTitle('');
      setContent('');
    } catch (err) {
      setError('发布帖子失败，请重试');
      console.error('发布帖子错误:', err);
    }
  };

  return (
    <Paper elevation={2} sx={{ p: 3, mb: 4 }}>
      <Typography variant="h6" sx={{ mb: 2 }}>
        发布新帖子
      </Typography>
      <Box component="form" onSubmit={handleSubmit} sx={{ '& > *': { mb: 2 } }}>
        <TextField
          fullWidth
          label="标题"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          error={Boolean(error && !title.trim())}
          helperText={error && !title.trim() ? '请输入标题' : ''}
          disabled={loading}
        />
        <TextField
          fullWidth
          multiline
          rows={4}
          label="内容"
          value={content}
          onChange={(e) => setContent(e.target.value)}
          error={Boolean(error && !content.trim())}
          helperText={error && !content.trim() ? '请输入内容' : ''}
          disabled={loading}
        />
        {error && (
          <Typography color="error" variant="body2">
            {error}
          </Typography>
        )}
        <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            type="submit"
            variant="contained"
            color="primary"
            disabled={loading}
            sx={{ minWidth: 120 }}
          >
            {loading ? <CircularProgress size={24} /> : '发布'}
          </Button>
        </Box>
      </Box>
    </Paper>
  );
};